# -*- coding: UTF-8 -*-
# 2023/11/19 17:02
import os
from tkinter.filedialog import askdirectory

from ttkbootstrap import Toplevel, Button, Frame, Label, IntVar
from ttkbootstrap.tooltip import ToolTip

from phone.class_page import class_page
from phone.hot_page import hot_page
from phone.new_page import new_page
from phone.phone_tools import phone_tool, get_page_img
from phone.phone_top_frame import phone_top_frame
from phone.search_page import search_page
from tools.get_configer import my_configer
from tools.get_icon import hot, new, search, confirm, select_all, set_save_path, mobile_phone
from tools.get_logger import get_logger
from tools.img_tool import set_pil_img, set_tkimage
from tools.input_validation import int_placeholder_Entry
from tools.pool_download_image import pool_download_image

configer = my_configer()
loger = get_logger()


class phone_wallpaper(Toplevel, phone_tool):
    """
    水平壁纸
    """

    def __init__(self, *args, **kwargs):
        Toplevel.__init__(self, *args, **kwargs)
        phone_tool.__init__(self)
        self.root = kwargs["master"]

        self.windows_init()
        self.setupUI()
        self.setlayout()
        self.setCallback()
        self.setBalloon()

    def windows_init(self):
        """
        窗口初始化配置
        """
        self.iconphoto(True, set_tkimage(mobile_phone, self))
        self.minsize(910, 800)
        self.place_window_center()  # 窗口居中

    def setupUI(self):
        """
        创建组件
        """
        self.phone_frame = Frame(self)
        self.btn_frame = Frame(self.phone_frame)

        # 热门
        self.hot_btn_img = set_pil_img(hot, (30, 30))
        self.hot_btn = Button(self.btn_frame, image=self.hot_btn_img, compound='bottom', text="热门")

        # 最新
        self.new_btn_img = set_pil_img(new, (30, 30))
        self.new_btn = Button(self.btn_frame, image=self.new_btn_img, compound='bottom', text="最新")

        # 搜索按钮
        self.search_btn_img = set_pil_img(search, (30, 30))
        self.search_btn = Button(self.btn_frame, image=self.search_btn_img, compound='bottom', text="搜一搜")

        # 确认下载按钮
        self.confirm_download_button_img = set_pil_img(confirm, (30, 30))
        self.confirm_download_button = Button(self.btn_frame, text="确认下载", image=self.confirm_download_button_img, compound='bottom')

        # 全部下载
        self.select_all_btn_img = set_pil_img(select_all, (30, 30))
        self.select_all_btn = Button(self.btn_frame, text="下载所有分类", image=self.select_all_btn_img, compound='bottom')

        # 下载数量
        self.number_of_downloads = IntVar(self, 100)
        self.number_of_downloads_entry = int_placeholder_Entry(self.btn_frame, placeholder="在此填写选择分类下载数量", textvariable=self.number_of_downloads, width=6)

        # 保存按钮,保存label
        self.save_path = os.path.abspath('./')
        self.save_to_button_img = set_pil_img(set_save_path, (30, 30))
        self.save_to_button = Button(self.btn_frame, text="保存至", image=self.save_to_button_img, compound='bottom')
        self.save_to_label = Label(self.btn_frame, text=self.save_path)

        # 下载分类布局--------------------------------------------------------------------------
        self.img_class_frame = phone_top_frame(self.class_id_cover_url_name_save_path_list,
                                               line_num=3,
                                               master=self.phone_frame)

    def setlayout(self):
        """
        组件布局
        """
        self.phone_frame.place(relx=0, rely=0, relwidth=1, relheight=1)

        self.btn_frame.place(relx=0, rely=0, relwidth=1, relheight=0.11)
        self.img_class_frame.place(relx=0, rely=0.11, relwidth=1, relheight=0.89)

        self.hot_btn.pack(side="left", padx=10)
        self.new_btn.pack(side="left", padx=10)
        self.search_btn.pack(side="left", padx=10)
        self.confirm_download_button.pack(side="left", padx=10)
        self.select_all_btn.pack(side="left", padx=10)
        self.number_of_downloads_entry.pack(side="left", padx=10)
        self.save_to_button.pack(side="left", padx=10)
        self.save_to_label.pack(side="left", padx=10)

        self.update()

    def setCallback(self):
        """
        设置组件回调方法
        """
        # 统一设置分类按钮回调
        for class_btn in self.img_class_frame.download_page_btn_list:
            _title = getattr(class_btn, "class_name")

            class_btn.bind("<Double-Button-1>", lambda x, title=_title: class_page(x,  # 分类按钮方便获取分类信息
                                                                                   title,  # 窗口标题
                                                                                   self,  # 子窗口子对象
                                                                                   resizable=(False, True)
                                                                                   ))

        # 热门按钮回调
        self.hot_btn.bind("<ButtonRelease-1>", lambda x: hot_page(x,  # 分类按钮方便获取分类信息
                                                                  "热门",  # 窗口标题
                                                                  self,  # 子窗口子对象
                                                                  resizable=(False, True)  # 窗口调整策略只允许垂直方向
                                                                  ))

        # 最新按钮回调
        self.new_btn.bind("<ButtonRelease-1>", lambda x: new_page(x,  # 分类按钮方便获取分类信息
                                                                  "最新",  # 窗口标题
                                                                  self,  # 子窗口子对象
                                                                  resizable=(False, True)  # 窗口调整策略只允许垂直方向
                                                                  ))

        # 搜索按钮回调
        self.search_btn.bind("<ButtonRelease-1>", lambda x: search_page(x,  # 分类按钮方便获取分类信息
                                                                        "搜索",  # 窗口标题
                                                                        self,  # 子窗口子对象
                                                                        resizable=(False, True)  # 窗口调整策略只允许垂直方向
                                                                        ))

        self.save_to_button.config(command=self.get_save_to_path)
        self.confirm_download_button.config(command=self.confirm_download_button_callback)
        self.select_all_btn.config(command=self.select_all_callback)

        loger.info(f"电脑壁纸窗口组件设置回调")

    def setBalloon(self):
        """

        :return:
        """
        ToolTip(self.confirm_download_button, "点击此处提交下载,会根据选择分类、设置数量、保存位置进行自动下载")
        ToolTip(self.save_to_button, "点击更新下载位置,默认保存位置为程序所在目录")
        ToolTip(self.number_of_downloads_entry, "此处设置每个分类下载壁纸数量,选择下载所有分类也会以此处设置为准进行下载")
        ToolTip(self.select_all_btn, "点击效果同选择所有分类后点击确认下载")

        loger.info(f"电脑壁纸窗口组件设置提示")

    def get_save_to_path(self):
        save_path = askdirectory(initialdir="./",
                                 parent=self,
                                 title="选择保存目录")

        if save_path in ["", None]:
            loger.info(f"未选择目录,忽略")
            return
        else:
            self.save_path = save_path
            self.save_to_label.config(text=save_path)

    def confirm_download_button_callback(self):
        """
        注意:分类窗口和热门几个需要信息不一致
        确认下载回调
        """
        loger.info(f"分类批量提交按照选择下载")
        download_id_name_list = self.img_class_frame.get_select_btn()

        if not download_id_name_list:
            loger.info("未选择分类忽略本次请求")
            return

        # 获取所有分类的对应图片地址
        all_download_list = list()
        for class_id, class_name in download_id_name_list:
            loger.info(f"准备提取{class_name}分类下载信息,id:{class_id}")
            _all_download_list = self.get_class_download_info(class_id, class_name)
            all_download_list += _all_download_list

        # 提交下载
        pool_download_image(all_download_list)

    def select_all_callback(self):
        """
        注意:分类窗口和热门几个需要信息不一致
        全选回调
        """
        download_id_name_list = self.img_class_frame.get_all_btn()
        loger.info(f"提交按照选择下载")

        # 获取所有分类的对应图片地址
        all_download_list = list()
        for class_id, class_name in download_id_name_list:
            loger.info(f"准备提取{class_name}分类下载信息,id:{class_id}")
            _all_download_list = self.get_class_download_info(class_id, class_name)
            all_download_list += _all_download_list

        # 提交下载
        pool_download_image(all_download_list)

    def get_class_download_info(self, class_id, class_name):
        """
        根据id获取,指定数量的信息
        [
            {"img_name": f'{"_".join(img_info["tag"])}_{img_info["id"]}.jpg',
             "img_id": img_info["id"],
             "img_tag": "-".join(img_info["tag"]),
             "img_urls":
                 {
                     "thumb": img_info["thumb"],  # 预览350*540
                     "img": img_info["img"],  # 标准大小1080*1920
                     "preview": img_info["preview"]  # 最大2000*300,存在损坏的
                 }
             } for img_info in response["res"]["vertical"]
        ]

        """
        # 判断保存目录
        class_save_path = os.path.join(self.save_path, class_name)
        if not os.path.exists(class_save_path):
            os.mkdir(class_save_path)

        # 页数
        if self.number_of_downloads.get() > 100:
            _page = self.number_of_downloads.get() % 100
            page_no_sum = self.number_of_downloads.get() // 100
            if _page != 0:
                page_no_sum += 1
        else:
            page_no_sum = 1

        # 准备提取下载图片地址
        _all_results_list = list()
        for page_no in range(page_no_sum):
            _result = get_page_img(class_id, 40, page_no)
            _all_results_list += _result

            loger.info(f"准备下载获取第{page_no + 1}页信息.")

        # 根据获得的总列表进行提取提交线程池下载
        _all_download_list = list()
        for tag_id_key_urls_dict in _all_results_list:
            _img_name = tag_id_key_urls_dict['img_name']  # tag里面已经有classid和图id
            _save_path = os.path.abspath(os.path.join(class_save_path, _img_name))
            _max_img_url = tag_id_key_urls_dict["img_urls"]["preview"]

            _all_download_list.append([_save_path, _max_img_url])

            loger.info(f"解析下载保存地址:{_max_img_url}, 图片url:{_save_path}")

        return _all_download_list
